from fastapi import APIRouter, Request, Depends, Form
from fastapi.responses import RedirectResponse, HTMLResponse
from fastapi.templating import Jinja2Templates
from sqlalchemy.orm import Session
from jose import jwt, JWTError
from auth.db import SessionLocal
from auth.utils import SECRET_KEY, ALGORITHM
from auth.models import User

router = APIRouter()
templates = Jinja2Templates(directory="templates")
def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

def get_current_user(request: Request, db: Session):
    token_cookie = request.cookies.get("access_token")
    if not token_cookie:
        return None
    try:
        token = token_cookie.split(" ")[1]
        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
        username = payload.get("sub")
        return db.query(User).filter(User.username == username).first()
    except JWTError:
        return None

# 查看个人信息
@router.get("/profile", response_class=HTMLResponse)
def profile_page(request: Request, db: Session = Depends(get_db)):
    user = get_current_user(request, db)
    if not user:
        return RedirectResponse(url="/login", status_code=303)
    return templates.TemplateResponse("profile.html", {"request": request, "user": user})

# 修改个人信息
@router.post("/profile/update")
def update_profile(
    request: Request,
    email: str = Form(None),
    phone: str = Form(None),
    password: str = Form(None),
    db: Session = Depends(get_db)
):
    user = get_current_user(request, db)
    if not user:
        return RedirectResponse(url="/login", status_code=303)

    if email:
        user.email = email
    if phone:
        user.phone = phone
    if password and len(password) >= 6:
        user.password = password  # ⚠️ 真实环境请加密保存
    db.commit()

    return RedirectResponse(url="/profile?msg=updated", status_code=303)
